﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BingWallPaper
{
    class Program
    {
        static void Main(string[] args)
        {
            SaveWallPaper();

        }

        private static void SaveWallPaper()
        {
            Bitmap bmpWallpaper;

            string ImageSavePath = @"D:\Program Files\BingWallpaper";
            //设置墙纸
            WebRequest webreq = WebRequest.Create(GetURL());
            WebResponse webres = webreq.GetResponse();

            DateTime dt = DateTime.Now;
            string dateStr = string.Format("{0:yyyyMMdd}", dt);
            string strSavePath = ImageSavePath + "\\bing" + dateStr + ".jpeg";


            using (Stream stream = webres.GetResponseStream())
            {
                bmpWallpaper = (Bitmap)Image.FromStream(stream);
                if (!Directory.Exists(ImageSavePath))
                {
                    Directory.CreateDirectory(ImageSavePath);
                }
                //设置文件名为例：bing2017816.jpg

                bmpWallpaper.Save(strSavePath, ImageFormat.Jpeg);
            }
            // 保存图片代码到此为止，下面就是
            //SetWallPaperApi(strSavePath);
        }
        // 获取壁纸Bing地址
        private static string GetURL()
        {
            string InfoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InfoUrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            string xmlDoc;
            // 使用using 自动注销HttpWebResponse
            using(HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
            {
                Stream stream = webResponse.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    xmlDoc = reader.ReadToEnd();
                }
            }
            // <url>/az/hprichbg/rb/SWFC_ZH-CN9558503653_1366x768.jpg</url>
            // 使用正则表达式解析标签（字符串）,当然你也可以使用XmlDocument类或XDocument类
            Regex regex = new Regex("<url>(?<MyUrl>.*?)</url>", RegexOptions.IgnoreCase);
            MatchCollection collection = regex.Matches(xmlDoc);

            // 取得匹配列表
            string ImageUrl = "http://www.bing.com" + collection[0].Groups["MyUrl"].Value;
            ImageUrl = ImageUrl.Replace("1366x768", "1920x1080");


            return ImageUrl;
        }

        // 利用系统的用户接口设置壁纸
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni
            );
        public static void SetWallPaperApi(string strSavePath)
        {
            SystemParametersInfo(20, 1, strSavePath, 1);
        }
    }
}
